package es.indra.druida.desktop.configurator.beans.converters;

import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import es.indra.druida.desktop.configurator.beans.Window;
import es.indra.druida.desktop.utils.DesktopWriter;

/**
 * The Class WindowConverter.
 */
public class WindowConverter {

	/**
	 * Bean array to json.
	 * 
	 * @param elems
	 *            the elems
	 * 
	 * @return the string
	 */
	public static String beanArrayToJson(Window[] elems)	{
		StringBuffer jsonRet=new StringBuffer();
		jsonRet.append("[");

		for ( int i = 0 ; i < elems.length ; i++) {
			Window elem=elems[i];
			if (i>0)
				jsonRet.append(",");
			jsonRet.append("{");	
			HashMap <String,String> propiedades=elem.get();
			Iterator<String> propNames = propiedades.keySet().iterator();
			boolean primPropEscrita=false;
		    while(propNames.hasNext()){
		    	String propName=propNames.next();
		    	String value=propiedades.get(propName);
				if (value!=null){
					if (primPropEscrita==false)
						primPropEscrita=true;
					else
						jsonRet.append(",");
					jsonRet.append(propName+":"+DesktopWriter.generaCadenaJavascript(value) );
				}
		    }
			jsonRet.append("}");		
		}
		jsonRet.append("]");
		return jsonRet.toString();
	}
	
	/**
	 * Json to bean array.
	 * 
	 * @param jsonIcons
	 *            the json icons
	 * 
	 * @return the window[]
	 * 
	 * @throws JSONException
	 *             the JSON exception
	 */
	public static Window[] jsonToBeanArray (String jsonIcons) throws JSONException	{
		JSONArray aVentanas = new JSONArray(jsonIcons);
		Window[] retBeans=new Window[aVentanas.length()];
		for (int r=0;r<aVentanas.length(); r++){
			JSONObject jsonObject= aVentanas.getJSONObject(r);
			HashMap <String,String> atributos=new HashMap <String,String>();
			Iterator i= jsonObject.keys();
			while(i.hasNext())	{
				String o = (String)i.next();
				if (!jsonObject.isNull(o))	
					atributos.put(o,jsonObject.getString(o));
			}
			retBeans[r]=new Window(atributos);
		}
		return retBeans;
	}
	
}

